package skean.yzsm.com.androidvideocache;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.danikula.videocache.CacheListener;
import com.danikula.videocache.HttpProxyCacheServer;
import com.danikula.videocache.file.FileCache;

import java.io.File;
import java.util.HashMap;

import skean.yzsm.com.androidvideocache.universalvideoview.UniversalMediaController;
import skean.yzsm.com.androidvideocache.universalvideoview.UniversalVideoView;

/**
 * 视频预览页面
 */
public class VideoViewActivity extends AppCompatActivity implements UniversalVideoView.VideoViewCallback, CacheListener {

    private static final String TAG = "VideoViewActivity";

    private UniversalVideoView vwPlayback;
    private UniversalMediaController umcController;

    private int currentPosition;
    private boolean isPlaying = false;
    private boolean isFullscreen = false;
    private boolean hideConfirmButton = false;

    private ProgressDialog dialog;
    private HttpProxyCacheServer proxy;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_view);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        initView();
        path = getIntent().getStringExtra("PATH");
        if (path == null) {
            Toast.makeText(this, "没有视频...", Toast.LENGTH_SHORT).show();
            finish();
        }
        vwPlayback.setVideoViewCallback(this);
        umcController.setButtonListener(listener);
        umcController.setTitle("视频预览");
        umcController.setUseConfirmButton(false);
        umcController.setFadeOutTime(0);
        umcController.show(0);
        proxy = App.getProxy(this);
        proxy.registerCacheListener(this, path);
        if (proxy.isCached(path)) {
            String wrappedPath = proxy.getProxyUrl(path);
            LogUtils.i(TAG, "缓存成功的Path", wrappedPath);
            vwPlayback.setVideoPath(wrappedPath);
            startPlay();
        } else {
            dialog = new ProgressDialog(this);
            dialog.setMessage("下载进度");
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setIndeterminate(false);
            dialog.setCancelable(true);
            dialog.setProgress(0);
            dialog.show();
            String wrappedPath = proxy.getProxyUrl(path);
            LogUtils.i(TAG, "未缓存的Path", wrappedPath);
            vwPlayback.setVideoPath(wrappedPath);
        }
    }

    private void initView() {
        vwPlayback = (UniversalVideoView) findViewById(R.id.previewView);
        umcController = (UniversalMediaController) findViewById(R.id.controller);
        vwPlayback.setMediaController(umcController);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        vwPlayback.stopPlayback();
        proxy.unregisterCacheListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isPlaying) {
            vwPlayback.pause();
            currentPosition = vwPlayback.getCurrentPosition();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPlaying) {
            vwPlayback.seekTo(currentPosition);
            vwPlayback.start();
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        listener.onBackClick();
    }

    ///////////////////////////////////////////////////////////////////////////
    // DELE
    ///////////////////////////////////////////////////////////////////////////

    private UniversalMediaController.ButtonListener listener = new UniversalMediaController.ButtonListener() {
        @Override
        public void onBackClick() {
            if (hideConfirmButton) finish();
            else {
                AlertDialog.Builder builder = new AlertDialog.Builder(VideoViewActivity.this);
                builder.setTitle("提示")
                       .setMessage("确认放弃这段视频吗?")
                       .setNegativeButton("取消", null)
                       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               finish();
                           }
                       })
                       .show();
            }
        }

        @Override
        public void onConfirmClick() {
            setResult(RESULT_OK);
            finish();
        }
    };

    @Override
    public void onScaleChange(boolean isFullscreen) {
        this.isFullscreen = isFullscreen;
//        if (isFullscreen) {
//            ViewGroup.LayoutParams layoutParams = mVideoLayout.getLayoutParams();
//            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
//            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
//            mVideoLayout.setLayoutParams(layoutParams);
//            //GONE the unconcerned views to leave room for video and controller
//            mBottomLayout.setVisibility(View.GONE);
//        } else {
//            ViewGroup.LayoutParams layoutParams = mVideoLayout.getLayoutParams();
//            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
//            layoutParams.height = this.cachedHeight;
//            mVideoLayout.setLayoutParams(layoutParams);
//            mBottomLayout.setVisibility(View.VISIBLE);
//        }
    }

    @Override
    public void onPause(MediaPlayer mediaPlayer) { // Video pause
        Log.d(TAG, "onPause UniversalVideoView callback");
    }

    @Override
    public void onStart(MediaPlayer mediaPlayer) { // Video start/resume to play
        Log.d(TAG, "onStart UniversalVideoView callback");
    }

    @Override
    public void onBufferingStart(MediaPlayer mediaPlayer) {// steam start loading
        Log.d(TAG, "onBufferingStart UniversalVideoView callback");
    }

    @Override
    public void onBufferingEnd(MediaPlayer mediaPlayer) {// steam end loading
        Log.d(TAG, "onBufferingEnd UniversalVideoView callback");
    }

    @Override
    public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
        if (percentsAvailable > 100) return;
        LogUtils.i(TAG, "percent:" + percentsAvailable, "文件路径", cacheFile.getAbsolutePath(), "URL", url);
        if (dialog != null) {
            dialog.setProgress(percentsAvailable);
            if (percentsAvailable == 100 && !cacheFile.getName().endsWith(FileCache.TEMP_POSTFIX)) {
                dialog.dismiss();
                vwPlayback.stopPlayback();
                vwPlayback.setVideoPath(proxy.getProxyUrl(url));
                startPlay();
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // CTRl
    ///////////////////////////////////////////////////////////////////////////

    private void startPlay() {
        vwPlayback.start();
        isPlaying = true;
    }
}
